package org.langcom.log;

import java.io.File;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.logging.LogManager;
import java.util.logging.Logger;

import org.eclipse.core.runtime.Platform;
import org.langcom.CommonProperties;

/**
 * Purposed for improving a log path - log into application directory and customize handlers configuration
 * 
 * A pattern consists of a string that includes the following special components that will be replaced at runtime:
 * <ul>
 * <li>"/" the local pathname separator
 * <li>"%a" the eclipse application directory
 * <li>"%t" the system temporary directory
 * <li>"%h" the value of the "user.home" system property
 * <li>"%g" the generation number to distinguish rotated logs
 * <li>"%u" a unique number to resolve conflicts
 * <li>"%%" translates to a single percent sign "%"
 * </ul>
 * 
 * @author nemo
 * 
 */
public class LookLogInit {

	private static final String H = "%a";
	private static final String JAVA_UTIL_LOGGING_FILE_HANDLER_PATTERN = "java.util.logging.FileHandler.pattern";
	private CommonProperties props;
	private Logger rootLogger;
	private String logPattern;

	@SuppressWarnings("nls")
	public LookLogInit() throws SecurityException, IOException, IllegalArgumentException, InstantiationException, IllegalAccessException, InvocationTargetException, NoSuchMethodException, ClassNotFoundException {
		loadProperties();
		rootLogger = LogManager.getLogManager().getLogger("");
		LookLog.setDefault(rootLogger == null);
		addHandlers(rootLogger);
	}

	@SuppressWarnings("nls")
	private void loadProperties() throws IOException {
		if ((Platform.getProduct() != null) && (Platform.getProduct().getDefiningBundle() != null)) {
			props = new CommonProperties("logging.properties");
		}
	}

	@SuppressWarnings("nls")
	private void addHandlers(Logger rootLogger) throws IOException, InstantiationException, IllegalAccessException, InvocationTargetException, NoSuchMethodException, ClassNotFoundException {
		logPattern = getProps().getString(JAVA_UTIL_LOGGING_FILE_HANDLER_PATTERN);
		if (logPattern.startsWith(H)) {
			String logPath = Platform.getInstanceLocation().getURL().getPath().substring(1);
			logPath = logPath.substring(0, logPath.length() - 1);
			new File(logPath).mkdirs();
			logPattern = logPattern.replaceFirst(H, logPath);
			getProps().setString(JAVA_UTIL_LOGGING_FILE_HANDLER_PATTERN, logPattern);
			Logger.getLogger(this.getClass().getName()).info("***Log to path : " + logPath);
		}
	}

	public CommonProperties getProps() {
		return props;
	}
}
